import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Button,
  Tabs,
  DatePicker,
  Input,
  Modal,
  Progress,
  message,
  Select,
} from 'antd';
import _ from 'lodash';
import router from 'umi/router';
import queryString from 'query-string';
import moment from 'moment';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import downloadFile from '@/utils/utils';
import DeclareModal from '../../components/DeclareModal';
import SearchPersonEs from '../../components/SearchPersonEs';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { Option } = Select;
@connect(({ dismiss, loading, publicdata, login }) => ({
  dismiss,
  loading: loading.models.dismiss,
  publicdata,
  login,
}))
@Form.create()
class Adjust extends PureComponent {
  state = {
    selectedRowKeys: [],
    selectedRows: [],
    params: {},
    copyAll: {},
    tableLoading: false,
    excelLoading: false,
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  componentDidMount() {
    const {
      location,
      dismiss: {
        pageData: { pagination },
        activeKey,
      },
      dispatch,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    const { isMenuLink } = queryString.parse(location.search);
    dispatch({
      type: 'dismiss/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(activeKey, pagination.current, pagination.pageSize);
    }
  }

  // 查找列表
  getList = (activeKey = '1', currentPage = 1, pageSize = 10, queryParam, isClear = true) => {
    const { dispatch, form } = this.props;
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
      });
    }
    form.validateFields(
      ['creName', 'dateArr', 'execState', 'empName', 'certNo'],
      (err, fieldsValue) => {
        if (err) return;
        let temp = fieldsValue;
        temp = queryParam || temp;

        const formFieldsValue = {};
        Object.keys(temp).forEach(key => {
          if (key === 'dateArr') {
            formFieldsValue.operBeginDate =
              (temp.dateArr && temp.dateArr[0] && temp.dateArr[0].valueOf()) || null;
            formFieldsValue.operEndDate =
              (temp.dateArr && temp.dateArr[1] && temp.dateArr[1].valueOf()) || null;
          } else if (key === 'creName') {
            // 处理对象结构
            formFieldsValue[key] = temp[key]?.label;
          } else {
            formFieldsValue[key] = temp[key] === undefined ? null : temp[key].trim();
          }
          delete formFieldsValue.dateArr;
        });
        formFieldsValue.retiredState = activeKey;
        dispatch({
          type: 'dismiss/updateModalData',
          payload: {
            formFieldsValue: temp,
            activeKey,
            formatFormFieldsValue: formFieldsValue,
          },
        });
        // 申报明细表参数
        const copyAll = {
          // 线上没开，暂用线下2
          declWay: 2,
          execStep: 2,
        };
        this.setState({
          params: formFieldsValue,
          copyAll,
        });
        const pageArg = { currentPage, pageSize };
        dispatch({
          type: 'dismiss/fetchList',
          payload: {
            pageArg,
            ...formFieldsValue,
          },
        });
      }
    );
  };

  // 网上办理
  applyOnline = () => {
    const {
      dismiss: {
        pageData: { list },
      },
    } = this.props;
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys || selectedRowKeys.length === 0) {
      if (list.length > 0) {
        this.applyOnlineAll();
      } else {
        message.warning('无退工数据可供操作');
      }
    } else {
      this.applyOnlineRows();
    }
  };

  // 全部数据网上办理
  applyOnlineAll = () => {
    const { dispatch } = this.props;
    const { params } = this.state;
    confirm({
      title: '是否对当前列表全部数据进行网上办理？',
      icon: <QuestionCircleOutlined />,
      okText: '是',
      cancelText: '否',
      onOk: () => {
        dispatch({
          type: 'dismiss/applyOnline',
          payload: {
            insEmpHireRetiredIds: [],
            ...params,
          },
        }).then(() => {
          this.setState({
            selectedRowKeys: [],
            selectedRows: [],
          });
        });
      },
      onCancel() {},
    });
  };

  // 选中行数网上办理
  applyOnlineRows = () => {
    const { dispatch } = this.props;
    const { selectedRows, params } = this.state;
    const ids = selectedRows.map(item => ({ insEmpHireRetiredId: item.insEmpHireRetiredId }));
    confirm({
      title: (
        <div>
          是否对当前列表<span className="emphasize-text">{selectedRows.length}</span>
          条数据进行网上办理？
        </div>
      ),
      icon: <QuestionCircleOutlined />,
      okText: '是',
      cancelText: '否',
      onOk: () => {
        dispatch({
          type: 'dismiss/applyOnline',
          payload: {
            insEmpHireRetiredIds: ids,
            ...params,
          },
        }).then(() => {
          this.setState({
            selectedRowKeys: [],
            selectedRows: [],
          });
        });
      },
      onCancel() {},
    });
  };

  // 标记已办理
  signHandle = () => {
    const {
      dismiss: {
        pageData: {
          pagination: { total },
        },
      },
    } = this.props;
    const { selectedRowKeys } = this.state;
    if (!total) {
      message.warning('无退工数据可供操作');
    } else {
      this.showHandleConfirm(selectedRowKeys);
    }
  };

  showHandleConfirm = selectedRowKeys => {
    const {
      dismiss: { activeKey },
    } = this.props;
    const inParam = selectedRowKeys;
    const tip = Number(activeKey) === 1 ? '待办理' : '办理失败';
    if (!selectedRowKeys.length) {
      message.warning(`请选择${tip}列表数据`);
      return;
    }
    const title = (
      <Fragment>
        <span className="emphasize-text">{selectedRowKeys.length}</span>条
      </Fragment>
    );

    confirm({
      title: (
        <div>
          是否对当前列表{title}
          数据进行标记已办理？
        </div>
      ),
      okText: '是',
      cancelText: '否',
      onOk: () => {
        this.signHandleData(inParam);
      },
    });
  };

  signHandleData = param => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dismiss/markDisComplete',
      payload: param,
    }).then(() => {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
      });
    });
  };

  // 下载
  download = (url, param) => {
    downloadFile(param, url, 'POST');
  };

  // 线下申报错误下载
  showUnderDownDeclErr = batNo => {
    Modal.warning({
      title: (
        <Row>
          <Row>以下数据为不可办理数据，请下载查看。</Row>
          <a
            onClick={() =>
              this.download('/osApi/insDeduDetExt/syncInsOnLineRetiredDeclErrMessage', { batNo })
            }
          >
            下载
          </a>
        </Row>
      ),
      okText: '关闭',
      okType: 'default',
      autoFocusButton: 'cancel',
    });
  };

  // 导出excel
  exportExcel = () => {
    const { selectedRows, params } = this.state;
    const ids = selectedRows.map(item => ({ insEmpHireRetiredId: item.insEmpHireRetiredId }));
    const obj = {
      ...params,
      insEmpHireRetiredIds: ids,
    };
    if (selectedRows.length) {
      this.setState({ excelLoading: true });
      downloadFile(obj, '/osApi/insDeduDetExt/exportExcel', 'POST', () => {
        this.setState({ excelLoading: false });
      });
    } else {
      confirm({
        title: '请选择数据，如不选择，默认导出当前条件下所有数据！',
        okText: '导出',
        icon: <QuestionCircleOutlined />,
        cancelText: '取消',
        onOk: () => {
          downloadFile(params, '/osApi/insDeduDetExt/exportExcel', 'POST');
        },
      });
    }
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    form.setFieldsValue({ dateArr: null });
    dispatch({
      type: 'dismiss/updateModalData',
      payload: { formFieldsValue: {} },
    });
  };

  // 切换form
  toggleForm = () => {
    const {
      dispatch,
      dismiss: { expandForm },
    } = this.props;
    dispatch({
      type: 'dismiss/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 渲染完整表单
  renderAdvancedForm = () => {
    const {
      form: { getFieldDecorator },
      dismiss: { formFieldsValue, activeKey, execStateList },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="申报状态" {...this.tableSearchLayout}>
              {getFieldDecorator('execState', {
                initialValue: formFieldsValue.execState,
              })(
                <Select
                  placeholder="请选择"
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                >
                  {execStateList.map(value => (
                    <Option value={value.itemCode} key={value.itemCode}>
                      {value.itemName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="操作时间" {...this.tableSearchLayout}>
              {getFieldDecorator('dateArr', {
                initialValue: formFieldsValue.dateArr,
              })(<RangePicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            {/* 20200921 后端要求表单改为下拉框选中项的label值 */}
            <FormItem label="所属客服" {...this.tableSearchLayout}>
              {getFieldDecorator('creName', {
                initialValue: formFieldsValue.creName,
              })(
                <SearchPersonEs
                  allowClear
                  showSearch
                  // 添加labelInValue可以把选中对象到处到表单中
                  labelInValue
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 渲染简单的表单
  renderSimpleForm = () => {
    const {
      form: { getFieldDecorator },
      dismiss: { formFieldsValue, activeKey },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  展开 <DownOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 展开搜索的表单项
  renderForm = () => {
    const {
      dismiss: { expandForm },
    } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  };

  // 切换页签
  tabChange = value => {
    const { location } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey: value,
      },
    });
    this.getList(value);
  };

  // 选中表格中一行时候
  handleSelectRows = (selectedRows, selectedKeys) => {
    const newRows = _.cloneDeep(selectedRows);
    const newKeys = _.cloneDeep(selectedKeys);
    this.setState({ selectedRows: newRows, selectedRowKeys: newKeys });
  };

  handleStandardTableChange = pagination => {
    const {
      dismiss: { activeKey },
    } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize, undefined, false);
  };

  // 申报明细表导出
  declareExport = () => {
    const {
      dismiss: {
        pageData: { list },
      },
      dispatch,
    } = this.props;
    const { selectedRows, params, copyAll } = this.state;
    const ids = selectedRows.map(item => ({ insEmpHireRetiredId: item.insEmpHireRetiredId }));
    if (list.length > 0) {
      dispatch({
        type: 'dismiss/declareExport',
        payload: {
          ...params,
          insEmpHireRetiredIds: ids,
        },
      }).then(res => {
        if (res.success) {
          this.setState({
            downParam: {
              deduDetIds: res.data.deduDetIds,
              ...copyAll,
            },
          });
          this.getDeclList(1, 5, res.data.deduDetIds);
        } else {
          message.warning(res.message || '服务端错误');
        }
      });
    } else {
      message.warning('无查询结果，不可导出！');
    }
  };

  // 申报明细表中查找列表
  getDeclList = (currentPage, pageSize, deduDetIds) => {
    const { dispatch } = this.props;
    const { copyAll } = this.state;
    this.setState({
      tableLoading: true,
    });
    dispatch({
      type: 'dismiss/getDeclList',
      payload: {
        deduDetIds,
        ...copyAll,
        // pagerArg: {
        //   currentPage,
        //   pageSize,
        // },
      },
    }).then(() => {
      this.setState({
        decExcelVisible: true,
        tableLoading: false,
      });
    });
  };

  // 下载点击
  downSingleClick = values => {
    const { downParam } = this.state;
    const { insDeclExportId } = values;
    downloadFile(
      {
        ...downParam,
        insDeclExportId,
      },
      '/osApi/insDeduDet/insDeclDetSingleExport',
      'POST'
    );
  };

  // 设置显隐
  onDeclareCancel = () => {
    this.setState({
      decExcelVisible: false,
    });
  };

  pageChange = (current, pageSizes) => {
    this.getDeclList(current, pageSizes);
  };

  pageSizeChange = (current, pageSizes) => {
    this.getDeclList(current, pageSizes);
  };

  // 点击确定
  onDeclareOk = () => {
    const { downParam } = this.state;
    downloadFile(downParam, '/osApi/insDeduDet/downloadDeclDetInsDeduImport', 'POST');
    this.setState({
      decExcelVisible: false,
    });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    const { queryParam } = location;
    await this.resetSearch();
    await this.getList(location.query.activeKey, undefined, undefined, queryParam);

    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const {
      dismiss: { pageData, activeKey, tabList, progressPercent, declData, showProgress },
      loading,
    } = this.props;
    const {
      selectedRowKeys,
      selectedRows,
      decExcelVisible,
      tableLoading,
      excelLoading,
    } = this.state;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '离职日期',
        dataIndex: 'evaDate',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => (text ? moment(text).format('YYYY-MM-DD') : '--'),
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => (text ? moment(text).format('YYYY-MM-DD') : '--'),
      },
      {
        title: '申报状态',
        dataIndex: 'execStateName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => text || '--',
      },
      {
        title: '所属客服',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '网报反馈',
        dataIndex: 'retiredExexFdbk',
        className: +activeKey === 4 ? styles.show : styles.hide,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作时间',
        dataIndex: 'operTime',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => text && moment(text).format('YYYY-MM-DD HH:mm'),
      },
    ];

    const tabArr1 = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="os:insDeduDetExt:syncInsOnLineRetiredDecl" noMatch={null}>
            <Button type="primary" onClick={this.applyOnline}>
              网上办理
            </Button>
          </Authorized>
          <Button onClick={this.signHandle} style={{ marginLeft: 8 }}>
            标记已办理
          </Button>
        </Row>
      </div>
    );

    const tabArr2 = null;

    const tabArr3 = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="os:insDeduDetExt:exportDeclResultDet" noMatch={null}>
            <Button type="primary" onClick={this.declareExport}>
              申报明细表导出
            </Button>
          </Authorized>
        </Row>
      </div>
    );

    const tabArr4 = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="os:insDeduDetExt:syncInsOnLineRetiredDecl" noMatch={null}>
            <Button type="primary" onClick={this.applyOnline} style={{ marginRight: 8 }}>
              网上办理
            </Button>
          </Authorized>
          <Button onClick={this.signHandle} style={{ marginRight: 8 }}>
            标记已办理
          </Button>
          <Authorized authority="os:insDeduDetExt:exportExcel" noMatch={null}>
            <Button onClick={this.exportExcel} style={{ marginRight: 8 }} loading={excelLoading}>
              导出Excel
            </Button>
          </Authorized>
        </Row>
      </div>
    );

    const tabArr = [tabArr1, tabArr2, tabArr3, tabArr4];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        {/* {this.selectedRowKeys} */}
        <Card className={styles.tabCard}>
          <div className={styles.tableList}>
            <Tabs activeKey={activeKey} onChange={this.tabChange}>
              {tabList.map((value, index) => (
                <TabPane tab={value.itemName} key={value.itemCode}>
                  {tabArr[index]}
                  <StandardTable
                    selectedRows={selectedRows}
                    loading={loading}
                    selectedRowKeys={selectedRowKeys}
                    data={pageData}
                    columns={columns}
                    rowKey="insEmpHireRetiredId"
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange}
                  />
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
        <Modal title="网上办理" footer={null} closable={false} visible={showProgress}>
          <div style={{ textAlign: 'center' }}>
            <div>
              <Progress
                percent={progressPercent}
                format={percent => `${percent}%`}
                style={{ paddingRight: 24, marginBottom: 20 }}
              />
            </div>
          </div>
        </Modal>
        <DeclareModal
          visible={decExcelVisible}
          dataSource={declData}
          tableLoading={tableLoading}
          downSingleClick={this.downSingleClick}
          onCancel={this.onDeclareCancel}
          pageChange={this.pageChange}
          pageSizeChange={this.pageSizeChange}
          onOk={this.onDeclareOk}
          declExportId="insDeclExportId"
          accoName="insAccoName"
        />
      </PageHeaderWrapper>
    );
  }
}

export default Adjust;
